package com.yatop.lalmbda.ai.service.impl;

import com.yatop.lalmbda.ai.TaskScheduler;
import com.yatop.lalmbda.ai.model.Account;
import com.yatop.lalmbda.ai.model.Task;
import com.yatop.lalmbda.ai.model.TaskDetail;
import com.yatop.lalmbda.ai.service.TaskService;
import com.yuyaogc.lowcode.engine.annotation.Service;
import com.yuyaogc.lowcode.engine.context.Context;
import com.yuyaogc.lowcode.engine.exception.EngineException;
import com.yuyaogc.lowcode.engine.plugin.activerecord.Criteria;

import java.sql.Timestamp;

@Service
public class TaskServiceImpl implements TaskService {
   private static  final TaskScheduler scheduler = new TaskScheduler();
    static {
        scheduler.startScheduler();
    }

    @Override
    public void create(Task task) {

        Account account =  Account.selectOne(Account.class, Criteria.equal("userId", Context.getInstance().getUserId()));
        if(null == account){
            throw new EngineException("当前账户为空");
        }

        task.setTaskBeginTime(new Timestamp(System.currentTimeMillis()));
        task.setCreateTime(new Timestamp(System.currentTimeMillis()));
        task.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        task.setTaskType("jpg");
        task.setTaskStatus("PENDING");
        task.setPriority("HIGH");
        task.setUserId(Context.getInstance().getUserId());
        task.setTaskEndTime(new Timestamp(System.currentTimeMillis()));
        task.save();




        Long taskId = task.getId();
        TaskDetail taskDetail = new TaskDetail();
        taskDetail.set("task", taskId);
        taskDetail.setUserId(Context.getInstance().getUserId());
        taskDetail.setCreateTime(new Timestamp(System.currentTimeMillis()));
        taskDetail.setTaskType("jpg");
        taskDetail.setTaskName(task.getTaskName());
        taskDetail.setTaskBeginTime(new Timestamp(System.currentTimeMillis()));
        taskDetail.setTaskEndTime(new Timestamp(System.currentTimeMillis()));
        taskDetail.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        taskDetail.save();


        scheduler.addTask(taskId, Context.getInstance());
    }
}
